package com.cec.controller;

import com.cec.exception.ResourcesException;
import com.cec.result.Result;
import com.cec.result.ResultCode;
import com.cec.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@Api(tags = "通用接口")
public class UploadController {

    private final AliOssUtil aliOssUtil;

    public UploadController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }

    @ApiOperation("文件上传")
    @PostMapping("/admin/upload")
    public Result adminUpload(@RequestParam("file") MultipartFile file){
        log.info("上传文件--->{}",file.getOriginalFilename());
        // 获取原文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 重命名文件名
        String newFileName = UUID.randomUUID().toString() + fileNameSuffix;
        try {
            // 上传文件
            String filePath = aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success("上传成功",filePath);
        } catch (IOException e) {
            //  throw new RuntimeException(e);
            log.info("上传文件失败--->{}",e.getMessage());
            throw new ResourcesException(ResultCode.RESOURCE_ERROR);
        }
    }

    @ApiOperation("文件上传")
    @PostMapping("/user/upload")
    public Result userUpload(@RequestParam("file") MultipartFile file){
        log.info("上传文件--->{}",file.getOriginalFilename());
        // 获取原文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 重命名文件名
        String newFileName = UUID.randomUUID().toString() + fileNameSuffix;
        try {
            // 上传文件
            String filePath = aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success("上传成功",filePath);
        } catch (IOException e) {
            //  throw new RuntimeException(e);
            log.info("上传文件失败--->{}",e.getMessage());
            throw new ResourcesException(ResultCode.RESOURCE_ERROR);
        }
    }
}
